#!/bin/bash

# Parse connection
for pair in ${1}; do
  eval "_pg_${pair}"
done

PSQL="/opt/gitlab/embedded/bin/psql -h ${_pg_host} -p ${_pg_port} -U ${_pg_user}"

psql() {
  PGPASSFILE="${PGPASSFILE:-}" ${PSQL} -d ${1:-template1}
}

PGTGRM_EXTENSION='pg_trgm'
BTREE_GIST_EXTENSION='btree_gist'
GITLAB_DATABASE_NAME='<%= @database_name %>'
GITLAB_SQL_USER='<%= @sql_user %>'
GITLAB_SQL_USER_PASSWORD='md5<%= @sql_user_password %>'
GITLAB_PGBOUNCER_USER='<%= @pgbouncer_user %>'
GITLAB_PGBOUNCER_PASSWORD='md5<%= @pgbouncer_user_password %>'
<% if @add_auth_function %>
GITLAB_AUTH_FUNCTION='<%= pg_helper.pg_shadow_lookup %>'
<% end %>

printf 'Creating %s user\n' ${GITLAB_SQL_USER}
psql <<-SQL
CREATE USER "${GITLAB_SQL_USER}" WITH LOGIN PASSWORD '${GITLAB_SQL_USER_PASSWORD}';
SQL

printf 'Creating %s user\n' ${GITLAB_PGBOUNCER_USER}
psql <<-SQL
CREATE USER "${GITLAB_PGBOUNCER_USER}" WITH LOGIN PASSWORD '${GITLAB_PGBOUNCER_PASSWORD}';
SQL

printf 'Creating %s database\n' ${GITLAB_DATABASE_NAME}
psql <<-SQL
CREATE DATABASE "${GITLAB_DATABASE_NAME}" WITH OWNER "${GITLAB_SQL_USER}";
SQL

printf 'Creating %s extension\n' ${PGTGRM_EXTENSION}
psql ${GITLAB_DATABASE_NAME} <<-SQL
CREATE EXTENSION IF NOT EXISTS "${PGTGRM_EXTENSION}";
SQL

printf 'Creating %s extension\n' ${BTREE_GIST_EXTENSION}
psql ${GITLAB_DATABASE_NAME} <<-SQL
CREATE EXTENSION IF NOT EXISTS "${BTREE_GIST_EXTENSION}";
SQL

[ -n "${GITLAB_AUTH_FUNCTION}" ] && psql ${GITLAB_DATABASE_NAME} < <( printf "${GITLAB_AUTH_FUNCTION}" )
